<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>密码修改</p>
    </header>
    
    <!-- 表单部分 -->
    <ul class="form-box">
      <li>
        <div class="title">
          用户名：
        </div>
        <div class="content">
          {{user.userName}}
        </div>
      </li>
      <li>
        <div class="title">
          原密码：
        </div>
        <div class="content">
          <input 
            v-model="user.oldPassword" 
            type="password" 
            placeholder="请输入原密码"
            :disabled="isProcessing">
        </div>
      </li>
      <li>
        <div class="title">
          新密码：
        </div>
        <div class="content">
          <input 
            v-model="user.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            :disabled="isProcessing">
        </div>
      </li>
      <li>
        <div class="title">
          确认密码：
        </div>
        <div class="content">
          <input 
            v-model="user.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            :disabled="isProcessing">
        </div>
      </li>
    </ul>
    
    <div class="button-login">
      <button @click="updatePassword" :disabled="isProcessing">
        {{ isProcessing ? '修改中...' : '确认修改' }}
      </button>
    </div>
    
    <!-- 底部菜单部分 -->
    <Footer></Footer>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-text">
        <i class="fa fa-spinner fa-spin"></i>
        加载中...
      </div>
    </div>
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
  name: 'ChangePassword',
  components: {
    Footer
  },
  data() {
    return {
      user: {
        userId: '',
        userName: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      isProcessing: false,
      loading: false
    }
  },
  async created() {
    this.loadUserInfo();
  },
  methods: {
    // 加载用户信息
    loadUserInfo() {
      const sessionUser = this.$getSessionStorage('user');
      if (sessionUser) {
        this.user.userId = sessionUser.userId;
        this.user.userName = sessionUser.userName;
      } else {
        this.$router.push('/login');
      }
    },
    
    // 修改密码
    async updatePassword() {
      // 验证输入
      if (!this.validateInput()) {
        return;
      }
      
      this.isProcessing = true;
      
      try {
        const response = await this.$axios.post(
          `/api/users/${this.user.userId}/password`,
          {
            oldPassword: this.user.oldPassword,
            newPassword: this.user.newPassword
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
        );
        
        if (response.data.success) {
          alert('密码修改成功！');
          this.logout();
        } else {
          this.handleError(response.data.message || '密码修改失败');
        }
      } catch (error) {
        console.error('密码修改失败:', error);
        this.handleApiError(error, '密码修改');
      } finally {
        this.isProcessing = false;
      }
    },
    
    // 输入验证
    validateInput() {
      if (!this.user.oldPassword) {
        alert('请输入原密码');
        return false;
      }
      
      if (!this.user.newPassword) {
        alert('请输入新密码');
        return false;
      }
      
      if (this.user.newPassword.length < 4 || this.user.newPassword.length > 100) {
        alert('新密码长度需在4-100个字符之间');
        return false;
      }
      
      if (this.user.newPassword !== this.user.confirmPassword) {
        alert('两次输入的新密码不一致');
        return false;
      }
      
      if (this.user.oldPassword === this.user.newPassword) {
        alert('新密码不能与原密码相同');
        return false;
      }
      
      return true;
    },
    
    // 处理API错误
    handleApiError(error, operation) {
      console.error(`${operation}失败:`, {
        message: error.message,
        status: error.response?.status,
        data: error.response?.data
      });
      
      if (error.response?.status === 401) {
        alert('用户未登录或会话已过期');
        this.$router.push('/login');
      } else if (error.response?.status === 400) {
        alert('请求参数错误');
      } else if (error.response?.status === 500) {
        alert('服务器内部错误，请稍后再试');
      } else if (error.response?.data?.message) {
        alert(`${operation}失败: ${error.response.data.message}`);
      } else {
        alert(`${operation}失败，请检查网络连接`);
      }
    },
    
    // 处理错误消息
    handleError(message) {
      alert(message);
    },
    
    // 修改成功后退出登录
    logout() {
      this.$removeSessionStorage('user');
      this.$router.push('/login');
    }
  }
}
</script>

<style scoped>
  /****************** 总容器 ******************/
  .wrapper {
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
  }

  /****************** header部分 ******************/
  .wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #0097FF;
    color: #fff;
    font-size: 4.8vw;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  /****************** 表单部分 ******************/
  .wrapper .form-box {
    width: 100%;
    margin-top: 12vw;
    padding: 0;
    list-style: none;
  }

  .wrapper .form-box li {
    box-sizing: border-box;
    padding: 4vw 3vw;
    display: flex;
    align-items: center;
    background-color: #fff;
    border-bottom: 1px solid #eee;
  }

  .wrapper .form-box li:last-child {
    border-bottom: none;
  }

  .wrapper .form-box li .title {
    flex: 0 0 25vw;
    font-size: 3.8vw;
    font-weight: 500;
    color: #333;
  }

  .wrapper .form-box li .content {
    flex: 1;
  }

  .wrapper .form-box li .content input {
    border: none;
    outline: none;
    width: 100%;
    height: 8vw;
    font-size: 3.8vw;
    background-color: transparent;
  }

  .wrapper .form-box li .content input:disabled {
    background-color: #f9f9f9;
    color: #999;
  }

  /****************** 修改按钮 ******************/
  .wrapper .button-login {
    width: 100%;
    box-sizing: border-box;
    padding: 6vw 3vw;
  }

  .wrapper .button-login button {
    width: 100%;
    height: 12vw;
    border: none;
    outline: none;
    border-radius: 6px;
    background-color: #00abf5;
    color: #fff;
    font-size: 4.5vw;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
  }

  .wrapper .button-login button:hover:not(:disabled) {
    background-color: #0095d9;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 171, 245, 0.3);
  }

  .wrapper .button-login button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  /****************** 加载状态 ******************/
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;
  }

  .loading-text {
    font-size: 4vw;
    color: #666;
    display: flex;
    align-items: center;
    gap: 2vw;
  }

  .loading-text .fa-spinner {
    font-size: 5vw;
  }

  /****************** 响应式设计 ******************/
  @media (min-width: 768px) {
    .wrapper header {
      height: 60px;
      font-size: 20px;
    }
    
    .wrapper .form-box {
      margin-top: 60px;
    }
    
    .wrapper .form-box li {
      padding: 15px 20px;
    }
    
    .wrapper .form-box li .title {
      flex: 0 0 120px;
      font-size: 16px;
    }
    
    .wrapper .form-box li .content input {
      height: 30px;
      font-size: 16px;
    }
    
    .wrapper .button-login {
      padding: 20px;
    }
    
    .wrapper .button-login button {
      height: 50px;
      font-size: 18px;
      max-width: 400px;
      margin: 0 auto;
      display: block;
    }
    
    .loading-text {
      font-size: 16px;
    }
    
    .loading-text .fa-spinner {
      font-size: 20px;
    }
  }
</style>